package co.yixiang.modules.system.util;

import co.yixiang.modules.shop.domain.YxUser;
import co.yixiang.modules.shop.service.YxUserService;
import co.yixiang.modules.system.enums.UserRoleEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class UserRoleUtil {


    private static YxUserService yxUserService;

    @Autowired
    public UserRoleUtil(YxUserService yxUserService) {
        UserRoleUtil.yxUserService = yxUserService;
    }

    /**
     * 为用户添加指定的角色
     * @param uid
     * @param merchant
     */
    public static void setUserRole(Integer uid, UserRoleEnum merchant) {
        YxUser user = yxUserService.findById(uid);
        String role = user.getUserRole();
        List<String> list = Arrays.stream(role.split(",")).collect(Collectors.toList());

        // 若用户不包含指定角色, 则增加相应角色
        if (!list.contains(merchant.value())) {
            list.add(merchant.value());
            String collect = String.join(",", list);
            user.setUserRole(collect);
            yxUserService.updateById(user);
        }
    }

    /**
     * 判断用户是否包含指定的角色
     * @param uid
     * @param userRole
     * @return
     */
    public static boolean checkUserRole(Integer uid, UserRoleEnum userRole) {
        boolean flag = false;
        YxUser user = yxUserService.findById(uid);
        String role = user.getUserRole();
        List<String> roleList = Arrays.stream(role.split(",")).collect(Collectors.toList());

        for (String roleNum : roleList) {
            if (userRole.value().equals(roleNum)) {
                flag = true;
                break;
            }
        }

        return flag;
    }


}
